/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.pivotcontrib.components;

import java.util.Comparator;
import java.util.Iterator;

import org.apache.pivot.collections.ArrayList;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.util.ImmutableIterator;
import org.apache.pivot.util.ListenerList;
import org.apache.pivot.wtk.Bounds;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.Container;
import org.apache.pivot.wtk.Theme;

import org.pivotcontrib.components.skin.TilePaneSkin;

/**
 * A container that arranges components into columns.
 */
public class TilePane extends Container {
    /**
     * A component tile in a tile pane.
     */
    public static final class Tile {
        private Component component;
        private int column;

        private TilePane tilePane = null;

        public Tile() {
            this(null, 0);
        }

        public Tile(Component component, int column) {
            this.component = component;
            this.column = column;
        }

        public Component getComponent() {
            return component;
        }

        public void setComponent(Component component) {
            if (tilePane != null) {
                throw new UnsupportedOperationException();
            }

            this.component = component;
        }

        public int getColumn() {
            return column;
        }

        public void setColumn(int column) {
            if (tilePane != null) {
                throw new UnsupportedOperationException();
            }

            if (column < 0) {
                throw new IllegalArgumentException("column must be positive.");
            }

            this.column = column;
        }

        public TilePane getTilePane() {
            return tilePane;
        }

        private void setTilePane(TilePane tilePane) {
            this.tilePane = tilePane;
        }
    }

    /**
     * Class that manages a tile pane's tile sequence. Callers get
     * access to the tile sequence via {@link TilePane#getTiles()}.
     */
    public final class TileSequence implements Sequence<Tile>, Iterable<Tile> {
        private TileSequence() {
        }

        @Override
        public int add(Tile tile) {
            int i = getLength();
            insert(tile, i);

            return i;
        }

        @Override
        public void insert(Tile tile, int index) {
            if (tile == null) {
                throw new IllegalArgumentException("tile is null.");
            }

            if (tile.getTilePane() != null) {
                throw new IllegalArgumentException
                    ("Tile already in use by another tile pane.");
            }

            Component component = tile.getComponent();

            if (component == null) {
                throw new IllegalArgumentException("Tile must have a component.");
            }

            tiles.insert(tile, index);
            tile.setTilePane(TilePane.this);

            TilePane.this.add(component);

            // Notify listeners
            tilePaneListeners.tileInserted(TilePane.this, index);
        }

        @Override
        public Tile update(int index, Tile tile) {
            throw new UnsupportedOperationException();
        }

        @Override
        public int remove(Tile tile) {
            int index = indexOf(tile);
            if (index != -1) {
                remove(index, 1);
            }

            return index;
        }

        @Override
        public Sequence<Tile> remove(int index, int count) {
            Sequence<Tile> removed = tiles.remove(index, count);

            if (count > 0) {
                for (int i = 0, n = removed.getLength(); i < n; i++) {
                    Tile tile = removed.get(i);
                    tile.setTilePane(null);

                    Component component = tile.getComponent();
                    TilePane.this.remove(component);
                }

                // Notify listeners
                tilePaneListeners.tilesRemoved(TilePane.this, index, removed);
            }

            return removed;
        }

        @Override
        public Tile get(int index) {
            return tiles.get(index);
        }

        @Override
        public int indexOf(Tile tile) {
            return tiles.indexOf(tile);
        }

        @Override
        public int getLength() {
            return tiles.getLength();
        }

        @Override
        public Iterator<Tile> iterator() {
            return new ImmutableIterator<Tile>(tiles.iterator());
        }
    }

    /**
     * Tile pane skin interface. Tile pane skins must implement
     * this interface to facilitate additional communication between the
     * component and the skin.
     */
    public interface Skin {
        public int getColumnAt(int x);
        public int getInsertionColumn(int x);
        public int getInsertionIndex(int column, int y, int columnSpan);
    }

    private enum Attribute {
        COLUMN_SPAN;
    }

    private static class TilePaneListenerList extends ListenerList<TilePaneListener>
        implements TilePaneListener {
        @Override
        public void tileInserted(TilePane tilePane, int index) {
            for (TilePaneListener listener : this) {
                listener.tileInserted(tilePane, index);
            }
        }

        @Override
        public void tilesRemoved(TilePane tilePane, int index,
            Sequence<TilePane.Tile> tiles) {
            for (TilePaneListener listener : this) {
                listener.tilesRemoved(tilePane, index, tiles);
            }
        }
    }

    private static class TilePaneAttributeListenerList
        extends ListenerList<TilePaneAttributeListener>
        implements TilePaneAttributeListener {
        @Override
        public void columnSpanChanged(TilePane tilePane, Component component,
            int previousColumnSpan) {
            for (TilePaneAttributeListener listener : this) {
                listener.columnSpanChanged(tilePane, component, previousColumnSpan);
            }
        }
    }

    static {
        Theme.getTheme().set(TilePane.class, TilePaneSkin.class);
    }

    private ArrayList<Tile> tiles = null;
    private TileSequence tileSequence = new TileSequence();

    private TilePaneListenerList tilePaneListeners = new TilePaneListenerList();
    private TilePaneAttributeListenerList tilePaneAttributeListeners =
        new TilePaneAttributeListenerList();

    /**
     * Creates a new <tt>TilePane</tt> with an empty tile sequence.
     */
    public TilePane() {
        this(new ArrayList<Tile>());
    }

    /**
     * Creates a new <tt>TilePane</tt> with the specified tiles.
     *
     * @param tiles
     * The tile sequence to use. A copy of this sequence will be made
     */
    public TilePane(Sequence<Tile> tiles) {
        if (tiles == null) {
            throw new IllegalArgumentException("tiles is null");
        }

        this.tiles = new ArrayList<Tile>(tiles);

        installThemeSkin(TilePane.class);
    }

    @Override
    protected void setSkin(org.apache.pivot.wtk.Skin skin) {
        if (!(skin instanceof TilePane.Skin)) {
            throw new IllegalArgumentException("Skin class must implement "
                + TilePane.Skin.class.getName());
        }

        super.setSkin(skin);
    }

    /**
     * Returns the tile pane's tile sequence.
     *
     * @return
     * The tile pane's tile sequence
     */
    public TileSequence getTiles() {
        return tileSequence;
    }

    public Tile getTileAt(int x, int y) {
        Tile tile = null;

        int i = tiles.getLength() - 1;
        while (i >= 0) {
            tile = tiles.get(i);
            Component component = tile.getComponent();

            if (component.isVisible()) {
                Bounds bounds = component.getBounds();
                if (bounds.contains(x, y)) {
                    break;
                }
            }

            i--;
        }

        if (i < 0) {
            tile = null;
        }

        return tile;
    }

    public int getColumnAt(int x) {
        TilePane.Skin tilePaneSkin = (TilePane.Skin)getSkin();
        return tilePaneSkin.getColumnAt(x);
    }

    public int getInsertionColumn(int x) {
        TilePane.Skin tilePaneSkin = (TilePane.Skin)getSkin();
        return tilePaneSkin.getInsertionColumn(x);
    }

    public int getInsertionIndex(int column, int y, int columnSpan) {
        TilePane.Skin tilePaneSkin = (TilePane.Skin)getSkin();
        return tilePaneSkin.getInsertionIndex(column, y, columnSpan);
    }

    @Override
    protected void layout() {
        super.layout();

        // Normalize the tile order
        ArrayList.<Tile>sort(tiles, new Comparator<Tile>() {
            @Override
            public int compare(Tile t1, Tile t2) {
                Component c1 = t1.getComponent();
                Component c2 = t2.getComponent();

                int result = c1.getY() - c2.getY();

                if (result == 0) {
                    result = c1.getX() - c2.getX();
                }

                return result;
            }
        });
    }

    /**
     * Overrides the base method to check whether or not a tile component is
     * being removed, which is not allowed (callers must use the <tt>Tile</tt>
     * method for that).
     *
     * @param index
     * The index at which components were removed
     *
     * @param count
     * The number of components removed
     *
     * @return
     * The sequence of components that were removed
     */
    @Override
    public Sequence<Component> remove(int index, int count) {
        for (int i = index, n = index + count; i < n; i++) {
            Component component = get(i);

            for (Tile tile : tiles) {
                if (tile.component == component) {
                    throw new UnsupportedOperationException();
                }
            }
        }

        // Call the base method to remove the components
        return super.remove(index, count);
    }

    /**
     * Returns the tile pane listener list.
     */
    public ListenerList<TilePaneListener> getTilePaneListeners() {
        return tilePaneListeners;
    }

    /**
     * Returns the tile pane attribute listener list.
     */
    public ListenerList<TilePaneAttributeListener> getTilePaneAttributeListeners() {
        return tilePaneAttributeListeners;
    }

    public static int getColumnSpan(Component component) {
        Integer value = (Integer)component.getAttribute(Attribute.COLUMN_SPAN);
        return (value == null) ? 1 : value;
    }

    public static void setColumnSpan(Component component, int columnSpan) {
        Integer previousValue = (Integer)component.setAttribute(Attribute.COLUMN_SPAN, columnSpan);
        int previousColumnSpan = (previousValue == null) ? 1 : previousValue;

        if (previousColumnSpan != columnSpan) {
            Container parent = component.getParent();

            if (parent instanceof TilePane) {
                TilePane tilePane = (TilePane)parent;
                tilePane.tilePaneAttributeListeners.columnSpanChanged(tilePane,
                    component, previousColumnSpan);
            }
        }
    }
}
